package net.pa.ovpn.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import net.pa.ovpn.constant.ovpnConstant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ovpnUtil {

	public static String getProperty(String key) throws Exception {
		Properties pros = getProperties();
		if(pros == null){
			throw new Exception("Property \"" + key + "\" not found.");
		}
		return (String) pros.get(key);
	}

	public static Properties getProperties() {
		Properties pros = null;
		String configurationFilepath = getConfigurationPath() + File.separator + ovpnConstant.configurationFileName;
		try {
			InputStream path = new FileInputStream(configurationFilepath);
			pros = new Properties();
			pros.load(path);
		} catch (FileNotFoundException e) {
			logger.error(configurationFilepath + " is missing.");
		} catch (IOException e) {
			logger.error(configurationFilepath + " load error.");
		}
		return pros;
	}

	public static String getConfigurationPath() {
		if (isWindows()) {
			return "C:/Documents and Settings/" + System.getProperty("user.name");
		} else {
			return "/etc/openvpn";
		}
	}

	public static boolean isWindows() {
		Properties prop = System.getProperties();
		String os = prop.getProperty("os.name");
		if (os.startsWith("win") || os.startsWith("Win")) {
			return true;
		} else {
			return false;
		}
	}	
	
	private static final Logger logger = LoggerFactory.getLogger(ovpnUtil.class);

}
